<template>
  <el-row>
    <el-col :span="24">
      <el-button class="mr20 mb5" style="float: right" @click="resetPatient">
        <template #icon>
          <i-ep-refresh/>
        </template>
        重置
      </el-button>
      <el-button class="mr20" style="float: right" type="primary" @click="readCard">
        <svg-icon class="mr5" icon-class="readCard"/>
        读卡
      </el-button>
    </el-col>
  </el-row>
  <div class="regist-info-div" style="height: calc(100% - 380px); padding-right: 20px">
    <div ref="registInfoDiv">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px"
               style="margin-top: 10px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="费别" prop="chargeType">
              <el-select v-model="form.chargeType" placeholder="请选择费别"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['medical_insurance_type']"
                           :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="初诊标志" prop="firstVisitIndicator">
              <el-radio-group v-model="form.firstVisitIndicator">
                <el-radio v-for="dict in dictDataMap['sys_yes_no']"
                          :key="dict.dictValue"
                          :value="dict.dictValue">{{
                    dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <!-- <el-form-item label="医保类别" prop="insuranceType">
                                    <el-input v-model="form.insuranceType" placeholder="请输入医保类别" />
                                </el-form-item> -->
            <el-form-item label="患者医保来源">
              <el-select v-model="form.source" placeholder="请选择费别"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['patient_medical_source']"
                           :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否急诊" prop="isEmergency">
              <el-radio-group v-model="form.isEmergency">
                <el-radio v-for="dict in dictDataMap['sys_yes_no']"
                          :key="dict.dictValue"
                          :value="dict.dictValue">{{
                    dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" clearable placeholder="请输入姓名"
                        @input="itemNameInput">
                <template #append>
                  <el-button class="patient-button" type="primary"
                             @click="patientSelectClick">查询
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号" v-bind:prop="isNotRequired === 'N' || !isOtcOutpatient ?'idNo' : ''">
              <el-input v-model="form.idNo" clearable placeholder="请输入证件号"
                        @change="certificateNoBlur">
                <template #prepend>
                  <el-select
                    v-model="form.certificateType"
                    clearable
                    placeholder="请选择证件类型"
                    style="width: 120px"
                  >
                    <el-option
                      v-for="dict in dictDataMap['certificate_type']"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <!--            <el-form-item label="出生日期" v-bind:prop="isNotRequired === 'N' || !isOtcOutpatient ?'birthdayDate' : ''">-->
            <el-form-item label="出生日期">
              <el-date-picker v-model="form.birthdayDate" clearable placeholder="请选择出生日期"
                              type="date" @change="birthdayDateChange"
                              value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别" v-bind:prop="isNotRequired === 'N' || !isOtcOutpatient ?'sex' : ''">
              <el-select v-model="form.sex" placeholder="请选择性别" style="width: 100%">
                <el-option v-for="dict in dictDataMap['sys_user_sex']"
                           :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-col :span="4" class="age-margin">
                <el-form-item label="年龄" v-bind:prop="isNotRequired === 'N' || !isOtcOutpatient ?'age' : ''">
                  <el-input ref="ageRef" v-model="form.age" class="age" clearable
                            placeholder="岁">
                    <template #append>岁</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4" class="age-margin">
                <el-form-item v-bind:prop="isNotRequired === 'N' || !isOtcOutpatient ?'ageMonth' : ''">
                  <el-input v-model="form.ageMonth" class="age" clearable
                            placeholder="月">
                    <template #append>月</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4" class="age-margin">
                <el-form-item v-bind:prop="isNotRequired === 'N' || !isOtcOutpatient ?'ageDay' : ''">
                  <el-input v-model="form.ageDay" class="age" clearable
                            placeholder="天">
                    <template #append>天</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4" class="age-margin">
                <el-form-item v-bind:prop="isNotRequired === 'N' || !isOtcOutpatient ?'ageHours' : ''">
                  <el-input v-model="form.ageHours" class="age" clearable
                            placeholder="时">
                    <template #append>时</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4" class="age-margin">
                <el-form-item v-bind:prop="isNotRequired === 'N' || !isOtcOutpatient ?'ageMinutes' : ''">
                  <el-input v-model="form.ageMinutes" class="age" clearable
                            placeholder="分">
                    <template #append>分</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4" class="age-margin">
                <el-button plain style="position: absolute; right: 0px"
                           type="primary" @click="resetAge">
                  清空
                </el-button>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" v-bind:prop="isNotRequired === 'N' || !isOtcOutpatient ?'phone' : ''">
              <el-input v-model="form.phone" clearable placeholder="请输入联系电话"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="婚姻" v-bind:prop="isNotRequired === 'N' || !isOtcOutpatient ?'marriage' : ''">
              <el-select v-model="form.marriage" placeholder="请选择婚姻状态"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['marriage_dict']"
                           :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="民族" prop="nation">
              <el-select v-model="form.nation" placeholder="请选择民族"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['nation_dict']"
                           :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="国籍" prop="nationality">
              <el-select v-model="form.nationality" placeholder="请选择国籍"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['nationality_dict']"
                           :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="乡组" prop="countryGroup">
              <el-input v-model="form.countryGroup" clearable placeholder="请输入乡组"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>


          <el-col :span="12">
            <el-form-item label="住址">
              <level-address :value="form.addressCode" style="width: 50%"
                             @handleChange="handleChangeAddressCode"/>
              <el-input v-model="form.address" clearable placeholder="请输入住址"
                        style="width: 50%"
                        @clear="clear"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="籍贯" prop="nativePlace">
              <el-input v-model="form.nativePlace" clearable placeholder="请输入籍贯"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生地" prop="homePlace">
              <el-input v-model="form.homePlace" clearable placeholder="请输入出生地"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="联系人关系" prop="contactsRelation">
              <el-select v-model="form.contactsRelation" placeholder="请选择联系人关系"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['relationship_dict']"
                           :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人" prop="contacts">
              <el-input v-model="form.contacts" placeholder="请输入联系人"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人身份证" prop="contactsIdNo">
              <el-input v-model="form.contactsIdNo" clearable
                        placeholder="请输入联系人身份证"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人地址" prop="contactsAddress">
              <el-input v-model="form.contactsAddress" clearable
                        placeholder="请输入联系人地址"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="联系人电话" prop="contactsPhone">
              <el-input v-model="form.contactsPhone" clearable
                        placeholder="请输入联系人电话"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="身份" prop="identity">
              <el-select v-model="form.identity" placeholder="请选择身份"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['profession_dict']"
                           :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="文化程度" prop="eduLevel">
              <el-select v-model="form.eduLevel" placeholder="请选择文化程度"
                         style="width: 100%">
                <el-option v-for="dict in dictDataMap['education_dict']"
                           :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="监护人姓名" prop="guardianName">
              <el-input v-model="form.guardianName" clearable
                        placeholder="请输入监护人姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="监护人电话" prop="guardianPhone">
              <el-input v-model="form.guardianPhone" clearable
                        placeholder="请输入监护人电话"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否公账" prop="isPublicAccounts">
              <el-radio-group v-model="form.isPublicAccounts">
                <el-radio v-for="dict in dictDataMap['sys_yes_no']"
                          :key="dict.dictValue"
                          :value="dict.dictValue">{{
                    dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item v-if="form.isPublicAccounts === 'Y'" label="统一社会信用代码" label-width="120"
                          prop="unifiedSocialCreditCode">
              <el-input v-model="form.unifiedSocialCreditCode" clearable
                        placeholder="请输入统一社会信用代码"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!--                <el-row>-->
        <!--                    <el-col :span="24">-->
        <!--                        <el-form-item label="初步诊断" prop="aaaa">-->
        <!--                            <el-input v-model="form.aaaa" clearable placeholder="请输入初步诊断"/>-->
        <!--                        </el-form-item>-->
        <!--                    </el-col>-->
        <!--                </el-row>-->
        <!-- <el-form-item label="医疗保险号" prop="insuranceNo">
                            <el-input v-model="form.insuranceNo" placeholder="请输入医疗保险号" />
                        </el-form-item>
                        <el-form-item label="医保就医登记流水号" prop="residenceNo">
                            <el-input v-model="form.residenceNo" placeholder="请输入医保就医登记流水号" />
                        </el-form-item> -->
      </el-form>
    </div>
  </div>
  <!-- 历史患者列表对话框 -->
  <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="75%">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleChange">
      <el-tab-pane :label="hisTitle" name="patientSelect">
        <patient-select ref="patientSelectRef" :api-source="'1'" :is-show-hours="false" :org-id="orgId"
                        @introduce="introduce"/>
      </el-tab-pane>
      <el-tab-pane :label="recodeTitle" name="recodePatient">
        <on-site-ambulance-station-select ref="recodeSelectRef" :api-source="'1'" :org-id="orgId"
                                          @introduce="introduce"/>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

import {useDictStoreHook} from "@/store/modules/dict";
import {allLetterResult} from "@/utils/pinyin.ts";
import axios from "axios";
import {ElMessage} from "element-plus";
import { selectConfigByCache } from "@/api/system/orgConfig.ts";
import { cardService } from "@/utils/Card.ts";

const emits = defineEmits(["saveRegister"]);
const {proxy} = getCurrentInstance() as any;
const patientSelectRef = ref();
const dictStore = useDictStoreHook();
let dictDataMap = ref(
  dictStore.isTypeGetData(
    "register_type",
    "payment_method",
    "patient_medical_source",
    "sys_yes_no",
    "medical_insurance_type",
    "sys_user_sex",
    "marriage_dict",
    "nation_dict",
    "nationality_dict",
    "relationship_dict",
    "profession_dict",
    "education_dict",
    "pay_way_dict",
    "certificate_type"
  )
);
const open = ref(false);
const title = ref("患者列表");
const hisTitle = ref("历史患者列表");
const recodeTitle = ref("门急诊记录患者列表");
//  门诊患者基本信息不必填（身份证、性别、年龄、出生日期、联系电话、婚姻）
const isNotRequired = ref("N")
const props = defineProps({
  orgId: {
    type: String,
    default: "",
  },
  // 是否来自便捷门诊
  isToConvenientOutpatient: {
    type: Boolean,
    default: false
  },
  // 是否来在OTC门诊  默认不是来自otc门诊
  isOtcOutpatient: {
    type: Boolean,
    default: false
  }
})
const form = ref<any>({
  recordNo: "",
  isPublicAccounts: "N",
  certificateType: "0",
  firstClinicRecord: "",
  firstOrder: "",
  firstCharge: "",
  firstExamConfirm: "",
  firstLabConfirm: "",
  firstTakeDrug: "",
  firstTakeZdrug: "",
  orgId: props.orgId,
  registType: "0",
  isEmergency: "N",
  patientId: "",
  visitNo: 0,
  clinicNo: "",
  registId: "",
  name: "",
  inputCode: "",
  sex: "1",
  age: 0,
  ageMonth: 0,
  ageDay: 0,
  ageHours: 0,
  ageMinutes: 0,
  phone: "",
  address: "",
  addressCode: "",
  idNo: "",
  guardianName: "",
  guardianPhone: "",
  birthdayDate: "",
  marriage: "10",
  weight: "",
  nation: "01",
  nationality: "CN",
  nativePlace: "",
  nativePlaceCode: "",
  zipCode: "",
  homePlace: "",
  homePlaceCode: "",
  countryGroup: "",
  contactsRelation: "",
  contacts: "",
  contactsIdNo: "",
  contactsAddress: "",
  contactsPhone: "",
  identity: "",
  eduLevel: "",
  chargeType: "1",
  insuranceType: "",
  source: "1",
  clinicSource: "",
  firstVisitIndicator: "Y",
  insuranceNo: "",
  residenceNo: "",
  unitInContract: "",
  unitEin: "",
  deptId: "",
  doctorId: "",
  clinicType: "",
  clinicChage: 0,
  registDate: "",
  registOperator: "",
  registNo: "",
  acctDateTime: "",
  referralNum: 0,
  acctNo: "",
  remarks: "",
  isPhy: "",
  tripCode: "",
  healthyCode: "",
  flag: "",
  chargeFlag: "",
  unattendedDoctor: "",
  registerFlag: "",
  serialNo: "",
  readFlag: "",
  ptPayId: "",
  otpErReflFlag: "",
  mdtrtGrpType: "",
  trumFlag: "",
  relTtpFlag: "",
  // 号表id
  clinicForRegistId: "",
  //记录id
  onSiteAmbulanceStationId: "",
  //就诊来源 挂号
  medicalSource: "0"
});
const rules = ref({
  idNo: [{required: true, message: "证件号不能为空", trigger: "blur"}],
  // idNo: [{required: true, validator: idNo, trigger: "blur"}],
  isEmergency: [{required: true, message: "是否急诊不能为空", trigger: "blur"}],
  birthdayDate: [{required: true, message: "出生日期不能为空", trigger: "change"}],
  sex: [{required: true, message: "性别不能为空", trigger: "blur"}],
  phone: [{required: true, message: "电话不能为空", trigger: "blur"}],
  marriage: [{required: true, message: "婚姻状态不能为空", trigger: "blur"}],
  address: [{required: true, message: "住址不能为空", trigger: "blur"}],
  name: [{required: true, message: "姓名不能为空", trigger: "blur"}],
  age: [{required: true, validator: ageValidator, trigger: "blur"}],
  ageMonth: [{required: false, validator: ageValidator, trigger: "blur"}],
  ageDay: [{required: false, validator: ageValidator, trigger: "blur"}],
  ageHours: [{required: false, validator: ageValidator, trigger: "blur"}],
  ageMinutes: [{required: false, validator: ageValidator, trigger: "blur"}],
});
const formRef = ref();

const activeName = ref('patientSelect');
const recodeSelectRef = ref();

// 年龄非空校验
function ageValidator(rule, _value, callback) {
  if (isNull(form.value.age)) {
    if (
      !isNull(form.value.age) ||
      !isNull(form.value.ageMonth) ||
      !isNull(form.value.ageDay) ||
      !isNull(form.value.ageHours) ||
      !isNull(form.value.ageMinutes)
    ) {
      formRef.value.clearValidate([
        "age",
        "ageMonth",
        "ageDay",
        "ageHours",
        "ageMinutes",
      ]);
      callback();
      return;
    } else {
      formRef.value.clearValidate(["ageMonth", "ageDay", "ageHours", "ageMinutes"]);
      callback(new Error(rule.message || "请输入年龄"));
    }
  } else {
    formRef.value.clearValidate(["age", "ageMonth", "ageDay", "ageHours", "ageMinutes"]);
    callback();
    return;
  }
}


function isNull(str) {
  if (str === "" || str === "0" || str === 0) {
    return true;
  } else {
    return false;
  }
}

// 读卡
function readCard() {
  try {
    const ws = new WebSocket('ws://localhost:36669');

    // 连接成功后的处理
    ws.onopen = () => {
      console.log('WebSocket连接已建立');
      // 发送读卡指令（如果需要）
      let data = { tsCode: '1003', picFilePath: "d:\\zp.bmp"}
      ws.send(JSON.stringify(data));
    };

    // 接收消息的处理
    ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      console.log('接收到消息:', data);

      if (data.code == '0') {
        const itemData = data.cardInfo.split("|");
        form.value.name = itemData[1];
        form.value.idNo = itemData[6];
        form.value.address = itemData[5];
        form.value.nativePlace = itemData[5];
        certificateNoBlur();
        itemNameInput(form.value.name);
      } else {
        ElMessage.error('身份证读取异常！' + data.errmsg);
      }
      // 关闭连接
      ws.close();
    };

    // 错误处理
    ws.onerror = (error) => {
      console.error('WebSocket错误:', error);
      ElMessage.error('读卡器连接异常，请检查设备是否连接！');
      ws.close();
    };

    // 连接关闭处理
    ws.onclose = () => {
      console.log('WebSocket连接已关闭');
    };
  } catch (error) {
    ElMessage.error('请检查读卡器设备是否连接~！');
  }

  // axios({
  //   url: 'http://localhost:8989/api/ReadMsg',
  //   method: 'get',
  //   params: {}
  // }).then((res) => {
  //   debugger
  //   var data = res.data;
  //   if (data.code == '0') {
  //     form.value.name = data.name;
  //     form.value.idNo = data.cardno;
  //     form.value.address = data.address;
  //     form.value.nativePlace = data.address;
  //     certificateNoBlur();
  //     itemNameInput(form.value.name);
  //   } else {
  //     ElMessage.error('身份证读取异常！' + data.errmsg);
  //   }
  // }).catch((r) => {
  //   ElMessage.error('请检查读卡器设备是否连接~！');
  // })
}


// 全部表单清空
function resetPatient() {
  formRef.value.resetFields();
  form.value.addressCode = null
}

/** 历史患者检索 */
function patientSelectClick() {
  open.value = true;
  activeName.value = 'patientSelect';
  nextTick(() => {
    const param = {
      name: form.value.name,
    };
    patientSelectRef.value.getParentList(param);
  });
}

// 身份证获取患者性别、出生年月日、年龄
function certificateNoBlur() {
  if (form.value.certificateType === "0") {
    const idNo = form.value.idNo;
    // 获取性别
    form.value.sex = proxy.$certificateNoInSex(idNo);
    // 获取出生年月日
    const birthday = proxy.$certificateNoInBirthday(idNo);
    form.value.birthdayDate = birthday;
    // 获取年龄 返回年月日小时对象
    const ageObj = proxy.$certificateNoInAge(birthday);
    if (ageObj) {
      form.value.age = ageObj.yStr;
      form.value.ageMonth = ageObj.mStr;
      form.value.ageDay = ageObj.dStr;
      form.value.ageHours = ageObj.hStr;
    }
  }
}

/**
 * 根据出生日期获取年龄
 */
function birthdayDateChange() {
// 获取年龄 返回年月日小时对象
  const ageObj = proxy.$certificateNoInAge(form.value.birthdayDate);
  if (ageObj) {
    form.value.age = ageObj.yStr;
    form.value.ageMonth = ageObj.mStr;
    form.value.ageDay = ageObj.dStr;
    form.value.ageHours = ageObj.hStr;
  }
}

/** 名称输入框改变事件 设置拼音码*/
function itemNameInput(value) {
  if (value) {
    form.value.inputCode = allLetterResult(value);
  } else {
    form.value.inputCode = "";
  }
}

// 年龄组清空
function resetAge() {
  form.value.age = 0;
  form.value.ageMonth = 0;
  form.value.ageDay = 0;
  form.value.ageHours = 0;
  form.value.ageMinutes = 0;
}

function clear() {
  form.value.addressCode = "";
}

/** 省市县区点击事件 */
function handleChangeAddressCode(obj: any) {
  if (obj) {
    form.value.addressCode = obj["townlet"].value;
    form.value.address =
      obj["economize"].label +
      obj["city"].label +
      obj["county"].label +
      obj["townlet"].label +
      form.value.address;
  }
}

/**
 * 保存数据校验
 */
function saveRegisterValidate() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      emits("saveRegister", form.value);
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false;
}

/** 引入历史患者信息 */
function introduce(row) {
  if (activeName.value === 'patientSelect') {
    form.value = toRaw(row);
  }
  form.value.visitDate = "";
  form.value.id = "";
  form.value.isNotShow = true;
  // 挂号
  form.value.medicalSource = "0";
  //便捷门诊
  if (props.isToConvenientOutpatient) {
    form.value.medicalSource = "2";
  }
  //OTC
  if (props.isOtcOutpatient) {
    form.value.medicalSource = "3";
  }
  // 身份证获取患者性别、出生年月日、年龄
  if (row.certificateType === '0' && row.idNo) {
    certificateNoBlur()
  }
  if (activeName.value === 'recodePatient') {
    form.value.onSiteAmbulanceStationId = row.onSiteAmbulanceStationId;
    form.value.name = row.name;
    form.value.sex = row.sex;
    form.value.age = row.age.toString().replace(/\D/g, '');
    form.value.nationality = findDictValue('nationality_dict', row.nationality); //默认中国
    form.value.nation = '01'; //默认汉族
    form.value.identity = findDictValue('profession_dict', row.shenfen);
    form.value.address = row.address; //住址
    form.value.phone = row.telephone; //联系电话
    form.value.inputCode = allLetterResult(form.value.name);
  }
  cancel();
}


function findDictValue(dictType: string, label) {
  const nationalityDict = dictDataMap.value[dictType];

  if (!Array.isArray(nationalityDict)) {
    return '';
  }
  const matchedDict = nationalityDict.find((dict: any) => dict.dictLabel === label);
  if (!matchedDict) {
    return '';
  }
  const dictValue = matchedDict.dictValue;
  return dictValue;

}

/**
 * 门诊患者基本信息不必填（身份证、性别、年龄、出生日期、联系电话、婚姻）
 */
function selectConfigByCacheFun() {
  // 便捷门诊可以不选诊断开药
  selectConfigByCache(props.orgId, "outp.patientInfo.isNotRequired").then((res => {
    isNotRequired.value = res.data.configValue
  }))
}

function handleChange(name) {
  nextTick(() => {
    const param = {
      name: form.value.name,
    };
    if (name === 'patientSelect') {
      patientSelectRef.value.getParentList(param);
    } else {
      recodeSelectRef.value.getParentList(param);
    }
  });

}

selectConfigByCacheFun()

defineExpose({
  saveRegisterValidate,
  resetPatient
})
</script>

<style scoped>


:deep(.patient-button) {
  background-color: #409eff !important;
  color: #ffffff !important;
}

:deep(.el-form-item__error) {
  width: 140px;
}

:deep(.age .el-input__inner) {
  width: 35px;
}

:deep(.el-input-group__append) {
  padding: 0 5px;
  width: 40px;
}

:deep(.el-tabs__content) {
  padding-bottom: 40px;
}
</style>
